package org.cleverframe.modules.erp.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.cleverframe.common.controller.BaseController;
import org.cleverframe.common.persistence.Page;
import org.cleverframe.common.utils.Encodes;
import org.cleverframe.common.vo.AjaxMessage;
import org.cleverframe.modules.erp.ErpBeanNames;
import org.cleverframe.modules.erp.ErpJspUrlPath;
import org.cleverframe.modules.erp.entity.RawMaterialInfo;
import org.cleverframe.modules.erp.service.RawMaterialInfoService;
import org.cleverframe.webui.easyui.data.DataGridJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * 原料资料Controller<br>
 * 
 * @author LiZW
 * @version 2015年12月21日 下午11:18:24
 */
@Controller
@RequestMapping("/${mvcPath}/erp")
@Transactional(readOnly = true)
public class RawMaterialInfoController extends BaseController
{
    /** 日志对象 */
    private final static Logger logger = LoggerFactory.getLogger(RawMaterialInfoController.class);
            
    @Autowired
    @Qualifier(ErpBeanNames.RawMaterialInfoService)
    private RawMaterialInfoService rawMaterialInfoService;

    /** 跳转到原料资料管理页面 */
    @RequestMapping("/getRawMaterialInfoJsp")
    public ModelAndView getRawMaterialInfoJsp(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView mav = new ModelAndView(ErpJspUrlPath.RawMaterialInfo);
        return mav;
    }

    /**
     * 跳转到原料库统计<br>
     */
    @RequestMapping("/getRawMaterialInventoryJsp")
    public ModelAndView getRawMaterialInventoryJsp(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView mav = new ModelAndView(ErpJspUrlPath.RawMaterialInventory);
        return mav;
    }
    
    /**
     * 查询原料资料，使用分页<br>
     * @return EasyUI DataGrid控件的json数据
     */
    @ResponseBody
    @RequestMapping("/findRawMaterialInfoByPage")
    public DataGridJson<RawMaterialInfo> findRawMaterialInfoByPage(
            HttpServletRequest request, 
            HttpServletResponse response,
            @RequestParam(value = "rawmaterialCode", required = false,defaultValue="") String rawmaterialCode,
            @RequestParam(value = "name", required = false,defaultValue="") String name,
            @RequestParam(value = "specification", required = false,defaultValue="") String specification,
            @RequestParam(value = "rawmaterialType", required = false,defaultValue="") String rawmaterialType,
            @RequestParam(value = "colorNo", required = false,defaultValue="") String colorNo)
    {
        name = "%" + name + "%";
        //specification = "%" + specification + "%";
        DataGridJson<RawMaterialInfo> json = new DataGridJson<RawMaterialInfo>();
        Page<RawMaterialInfo> page = rawMaterialInfoService.findRawMaterialInfoByPage(
                new Page<RawMaterialInfo>(request, response), 
                rawmaterialCode, name,specification, rawmaterialType, colorNo);
        json.setRows(page.getList());
        json.setTotal(page.getCount());
        return json;
    }
    
    /**
     * 增加原料资料
     * @return
     */
    @ResponseBody
    @RequestMapping("/addRawMaterialInfo")
    @Transactional(readOnly = false)
    public AjaxMessage addRawMaterialInfo(
            HttpServletRequest request, 
            HttpServletResponse response, 
            @Valid RawMaterialInfo rawMaterialInfo,
            BindingResult bindingResult)
    {
        AjaxMessage message = new AjaxMessage(true);
        if (beanValidator(bindingResult, message))
        {
            if (rawMaterialInfoService.addRawMaterialInfo(rawMaterialInfo, message))
            {
                message.setMessage("保存原料资料成功!");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
    }
    
    /**
     * 更新原料信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateRawMaterialInfo")
    @Transactional(readOnly = false)
    public AjaxMessage updateRawMaterialInfo( 
            HttpServletRequest request, 
            HttpServletResponse response, 
            @Valid RawMaterialInfo rawMaterialInfo,
            BindingResult bindingResult)
    {
        AjaxMessage message = new AjaxMessage(true);
        if (beanValidator(bindingResult, message))
        {
            if (rawMaterialInfoService.updateRawMaterialInfo(rawMaterialInfo, message))
            {
                message.setMessage("更新原料资料成功!");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
    }
    
    /**
     * 删除原料信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteRawMaterialInfo")
    @Transactional(readOnly = false)
    public AjaxMessage deleteRawMaterialInfo( 
            HttpServletRequest request, 
            HttpServletResponse response, 
            @Valid RawMaterialInfo rawMaterialInfo,
            BindingResult bindingResult)
    {
        AjaxMessage message = new AjaxMessage(true);
        if (beanValidator(bindingResult, message))
        {
            if (rawMaterialInfoService.deleteRawMaterialInfo(rawMaterialInfo, message))
            {
                message.setMessage("删除原料资料成功!");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
    }
    
    /** 
     * 导出数据
     * */
    @ResponseBody
    @RequestMapping("/exportRawMaterialInfo")
    public AjaxMessage exportRawMaterialInfo(
            HttpServletRequest request, 
            HttpServletResponse response, 
            @RequestParam(value = "ids", required = false,defaultValue="") String ids)
    {
        AjaxMessage message = new AjaxMessage(false);
        List<RawMaterialInfo> rawMaterialInfoList = null;
        if ("ALL".equalsIgnoreCase(ids))
        {

        }
        else
        {
            rawMaterialInfoList = rawMaterialInfoService.findRawMaterialInfoByIds(ids);
        }
        
        if (rawMaterialInfoList == null || rawMaterialInfoList.size() <= 0)
        {
            message.setMessage("查询不到导出的数据");
            return message;
        }
        else
        {
            // 文件存在，下载文件
            String filename = Encodes.browserDownloadFileName(request.getHeader("User-Agent"), "原料资料导出.xls");
            response.setContentType("multipart/form-data");
            // response.setHeader("Content-Disposition", "attachment;");
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            // response.setHeader("Content-Length", fileInfo.getFileSize().toString());
            try
            {
                OutputStream outputStream = response.getOutputStream();
                HSSFWorkbook workbook = rawMaterialInfoService.exportRawMaterialInfo(rawMaterialInfoList);
                workbook.write(outputStream);
                workbook.close();
                return null;
            }
            catch (IOException e)
            {
                logger.error("数据导出失败或取消", e);
                message.setMessage("数据导出失败或取消");
            }
        }
        return message;
    }
    
    /**
     * 导入数据
     * */
    @ResponseBody
    @RequestMapping("/importRawMaterialInfo")
    @Transactional(readOnly = false)
    public AjaxMessage importRawMaterialInfo(HttpServletRequest request, HttpServletResponse response)
    {
        AjaxMessage message = new AjaxMessage(false);
        // 保存上传文件
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (fileMap.size() != 1)
        {
            message.setMessage("数据导入只能上传一个文件,当前上传文件数：" + fileMap.size());
            return message;
        }
        Set<String> fileSet = fileMap.keySet();
        for (String filename : fileSet)
        {
            MultipartFile file = fileMap.get(filename);
            InputStream inputStream;
            try
            {
                inputStream = file.getInputStream();
                HSSFWorkbook workbook = rawMaterialInfoService.importRawMaterialInfo(inputStream);
                String resultFilename = Encodes.browserDownloadFileName(request.getHeader("User-Agent"), "原料资料导入结果.xls");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=" + resultFilename);
                OutputStream outputStream = response.getOutputStream();
                workbook.write(outputStream);
                inputStream.close();
                workbook.close();
                return null;
            }
            catch (Exception e)
            {
                logger.error("数据导入失败或取消", e);
                message.setMessage("数据导入失败或取消");
            }
            break;
        }
        return message;
    }
    
    /**
     * 模糊查询原料信息，使用分页<br>
     * */
    @ResponseBody
    @RequestMapping("/findRawMaterialInfoByParam")
    public List<RawMaterialInfo> findRawMaterialInfoByParam(
            HttpServletRequest request, 
            HttpServletResponse response,
            @RequestParam(value = "q", required = false, defaultValue = "") String q)
    {
        q = "%" + q + "%";
        Page<RawMaterialInfo> page = new Page<RawMaterialInfo>(1, 50);
        page = rawMaterialInfoService.findRawMaterialInfoByParam(page, q);
        return page.getList();
    }
    
    /**
     * 查询供应商供应的原料<br>
     * */
    @ResponseBody
    @RequestMapping("/findSupplierRawmaterial")
    public DataGridJson<RawMaterialInfo> findSupplierRawmaterial(
            HttpServletRequest request, 
            HttpServletResponse response, 
            @RequestParam(value = "supplierId", required = true) Long supplierId)
    {
        DataGridJson<RawMaterialInfo> json = new DataGridJson<RawMaterialInfo>();
        Page<RawMaterialInfo> page = rawMaterialInfoService.findSupplierRawmaterial(new Page<RawMaterialInfo>(request, response), supplierId);
        json.setRows(page.getList());
        json.setTotal(page.getCount());
        return json;
    }
    
    /**
     * 查询原料库存信息<br>
     * */
    @ResponseBody
    @RequestMapping("/findRawmaterialInventory")
    public DataGridJson<Map<Object, Object>> findRawmaterialInventory(
            HttpServletRequest request, 
            HttpServletResponse response, 
            @RequestParam(value = "rawmaterialCode", required = false,defaultValue="") String rawmaterialCode,
            @RequestParam(value = "name", required = false,defaultValue="") String name,
            @RequestParam(value = "specification", required = false,defaultValue="") String specification)
    {
        name = "%" + name + "%";
        specification = "%" + specification + "%";
        DataGridJson<Map<Object, Object>> json = new DataGridJson<Map<Object, Object>>();
        Page<Map<Object, Object>> page = new Page<Map<Object, Object>>(request, response);
        rawMaterialInfoService.findRawmaterialInventory(page, rawmaterialCode, name, specification);
        json.setRows(page.getList());
        json.setTotal(page.getCount());
        return json;
    }
}
